package com.jk.demo.thread;

/**
 * 停止线程的方法:
 * 1.stop暴力停止:
 * 2.捕获异常法:
 * 3.通过守护进程
 */
public class ThreadStopMethod {

    /**
     * 添加标记点:
     * 任务类型:自定义轮询任务
     * 计数器:每次加1,每秒count加10,到100停止
     */
    static int count = 0;
    static boolean flag = true;

    public static void testOne() {


        final Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (flag) {
                    System.out.println("working ...." + count);
                    try {
                        count++;
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (count == 100) {
                        flag = false;
                    }
                }

            }
        });
        thread.start();

    }

    /**
     * 线程不会中断,会持续运行
     */
    public static void interruptThread() {
        Thread thread = new Thread(() -> {
            while (true) {
                System.out.println("线程依旧存活:_此时计数器状态为_" + ++count);
                try {
                    Thread.currentThread().sleep(1_000);
                } catch (InterruptedException e) {
                }

            }
        }, "测试线程");
        thread.start();
        thread.interrupt();
    }

    /**
     * 线程不会中断会持续运行,但是会发现,在刚开始执行的时候捕捉到了一次 InterruptedException 异常
     * 如果想要停止线程那么就得需要在异常中做一些处理,线程持续运行的关键在于while循环阻塞了,那么想办法停止while循环才是关键
     * 详细看interruptThread3
     *
     * 第二种方式就是,判断当前线程是不是 interrupt 状态
     */
    public static void interruptThread2() {
        Thread thread = new Thread(() -> {
            while (true) {
                System.out.println(Thread.currentThread().getName() + "正在运行~");
                if (Thread.currentThread().isInterrupted()) {
                    System.out.println(Thread.currentThread().getName() + "接收到中断异常");
                    break;
                }
            }

        }, "测试线程");
        thread.start();
        thread.interrupt();
    }

    public static void interruptThread3() {

        Thread thread = new Thread(() -> {
            while (flag) {
                System.out.println(Thread.currentThread().getName() + "正在运行~");
                try {
                    Thread.currentThread().sleep(2_500);

                } catch (InterruptedException e) {
                    flag = false;
                    System.out.println(Thread.currentThread().getName() + "接收到中断异常");
                }
            }

        }, "测试线程");
        thread.start();
        thread.interrupt();
    }

    public static void main(String[] args) {
        interruptThread2();
    }
}
